package com.oocl.euc.common.utils;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class StringUtil {

    private StringUtil(){}

    public static String ignoreRepeat(String str) {
        if (str == null){
            return "";
        }
        return Arrays.stream(str.split(";")).distinct().filter(email -> email != "").collect(Collectors.joining(";"));
    }

    public static String rtrim(String s, char c) {
        if (s.endsWith(Character.toString(c))) {
            int i = s.lastIndexOf(c);
            if (i > 0)
                return s.substring(0, i);
        }
        return s;
    }

    public static boolean isEmailAddress(String email) {
        boolean tag = true;
        final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        final Pattern pattern = Pattern.compile(pattern1);
        final Matcher mat = pattern.matcher(email);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    public static String handleStr2(String str) {
        Pattern p = Pattern.compile("\t|\r|\n");
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    public static String getStrByAddBrForStr(String str, int startIndex) {
        if (str != null && !str.isEmpty()) {
            if (str.length() <= startIndex || str.contains("startUIbr/endUI")) {
                return str;
            } else {
                int index;
                StringBuilder sb = new StringBuilder();
                str = StringUtil.handleStr2(str);
                for (index = 0; index < str.length(); index += startIndex) {
                    if (index + startIndex <= str.length())
                        sb.append(str.substring(index, index + startIndex) + "startUIbr/endUI");
                    else
                        sb.append(str.substring(index, str.length()));
                }
                return sb.toString();
            }
        } else {
            return str;
        }
    }

    public static String replaceSeparator(String mailString) {
        return mailString.replaceAll(",", ";").replaceAll("\n", ";").replaceAll("\r", ";");
    }
}
